# python-resmon - Python tools for Resmon monitoring and the Circonus API
# Copyright (c) 2010 Crown coypright
# 
# This file is part of python-resmon.
# 
# python-resmon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# python-resmon is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with python-resmon.  If not, see <http://www.gnu.org/licenses/>.

import json

from alert import *
from status import StatusService

import SocketServer
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler


def get_json_struct(service):
    alerts = []
    for a in service.get_alerts():
        d = {
            'host': a.host.hostname,
            'severity': a.severity,
            'type': a.__class__.__name__,
            'cleared': isinstance(a, Restored),
            'alert': a.alert_string()
        }
        try:
            d['metric'] = a.metric.get_human_name()
            d['uid'] = '%s`%s' % (a.host.hostname, a.metric.name)
        except AttributeError:
            d['uid'] = '%s`error' % a.host.hostname

        try:
            d['value'] = a.get_formatted_value()
        except AttributeError:
            pass
        alerts.append(d)
    alerts.sort(key=lambda a: a['severity'])
    return alerts


class StatusRequestHandler(SimpleHTTPRequestHandler):
    def do_json(self):
        js = json.dumps(get_json_struct(self.status_service))
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Content-Length', str(len(js)))
        self.end_headers()
        self.wfile.write(js)

    def do_GET(self):
        if self.path == '/':
            try:
                ua = self.headers['User-Agent']
            except KeyError:
                ua = '-'

            if any([q in ua for q in ['Mobile', 'Android', 'iPhone']]):
                self.path = '/assets/mobile.html'
            else:
                self.path = '/assets/index.html'

        if self.path == '/status/json':
            self.do_json()
        else:
            SimpleHTTPRequestHandler.do_GET(self)


class Server(SocketServer.ThreadingMixIn, HTTPServer):
    """A threaded webserver."""


def start_server(address='', port=8000):
    status = StatusService()
    status.start()

    handler = StatusRequestHandler
    handler.status_service = status

    httpd = Server((address, port), handler)
    httpd.serve_forever()
    return httpd
